package pecas.pecasclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils.TruncateAt;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
 
public class HomeActivity extends Activity {
	// begin socket
	
	private static final int UDP_SERVER_PORT = 9050;	
	private static final int MAX_UDP_DATAGRAM_LEN = 1024;
	public static final int FINISHED_RECEIVER = 0;
	DatagramSocket udpReceiver = null;
	private LinearLayout llayout;
    private LinearLayout TRow;
    private LinearLayout TB;
    private TextView TextV;
    private ImageView ImageV;
    private EditText EditT;
    private DigitalClock Clock;
	Boolean isconnect = false;
	// end socket
	
	// load Image
	
	private static int RESULT_LOAD_IMAGE = 1;
	
	// end image
	String picturePath,picture1,picture2,picture3,picture4,picture5,picture6;
	Properties prop;
	
	TextView chuchay;
	int nguoi = 0;
	ImageView Nguoi1,Nguoi2,Nguoi3,Nguoi4,Nguoi5,Nguoi6;
	ImageView ImageA1,ImageA2,ImageA3,ImageA4,ImageA5,ImageA6,ImageA7,ImageA8,ImageA9,ImageA10;
	ImageView ImageB1,ImageB2,ImageB3,ImageB4,ImageB5,ImageB6,ImageB7,ImageB8,ImageB9,ImageB10;
	ImageView C1,C2,C3,C4;
	
	ImageView D1,D2,D3,D4,D5,D6,D7,D8,D9,D10,E3;
	TextView A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,F2,F3;
	TextView gd1,gd2,gd3,gd4,gd5,gd6,gd7,gd8,gd9,gd10;	
	EditText Gopytext,E1,F1,F4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //if (android.os.Build.VERSION.SDK_INT > 9) {
		  //    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		  //    StrictMode.setThreadPolicy(policy);
	    //}
        //DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
        
        
        if(GetConfig("IDLine").compareTo("") == 0 && GetConfig("PathFile").compareTo("") == 0)
        {
        	Log.i("Duong", "Open form cofig" );
        	Intent newActivity = new Intent(getApplicationContext(),ConfigActivity.class);
        	startActivity(newActivity);
        	Log.i("Duong", "Load Form main" );    
        	
        }
        else   
        {
        	Log.i("Duong", "Tao form" );
        	GetFormData("1");
        	setContentView(llayout);
        	SetValueDefault();
        	SetTime();
        }
        new LongOperation().execute("1");
    }

	private void SetTime() {
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		Date currentLocalTime = cal.getTime();		
		DateFormat date = new SimpleDateFormat("dd:MM:yy");  
		date.setTimeZone(TimeZone.getTimeZone("GMT")); 
		DateFormat time = new SimpleDateFormat("hh:mm:ss");  
		time.setTimeZone(TimeZone.getTimeZone("GMT")); 
		String localDate = date.format(currentLocalTime); 
		String localTime = time.format(currentLocalTime); 
		TextV = (TextView) findViewById(202);		
		TextV.setText(localDate);
		
	}


	private void GetFormData(String formNumber) {
		try {
			
			
			String sdcard=Environment.getExternalStorageDirectory().getAbsolutePath();
			String xmlfile=sdcard+"/Download/xmlgui" + formNumber + ".xml";
			File checkfile = new  File(xmlfile);
			if(!checkfile.exists()){
				xmlfile = GetConfig("PathFile");
			}
			Log.e("PathFile",xmlfile);
			FileInputStream fIn=new FileInputStream(xmlfile);
			InputStream is = fIn;			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = factory.newDocumentBuilder();
			Document dom = db.parse(is);
			Element root = dom.getDocumentElement();
			NodeList forms = root.getElementsByTagName("form");
			if (forms.getLength() < 1) {
				// nothing here??
				Log.e("ss","No form, let's bail");
				showMsg(xmlfile);
				return;
			}
			llayout = new LinearLayout(this);
			llayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));
			llayout.setPadding(10, 10, 0, 0);
			llayout.setOrientation(LinearLayout.VERTICAL);
			Node form = forms.item(0);
			NamedNodeMap attf = form.getAttributes();
			llayout.setBackgroundColor(Color.parseColor(attf.getNamedItem("BackgroundColor").getNodeValue()));
			Log.e("ss","sssfd");
			
			// now process the row width height
			NodeList row = root.getElementsByTagName("Row");
			for (int i=0;i<row.getLength();i++) 
			{									
				Node fieldNode = row.item(i);				
				NamedNodeMap attr = fieldNode.getAttributes();
				TRow = new LinearLayout(this);	
				int height = 100;	
				for (int a=0; a < attr.getLength(); a++) 
				{
					Attr node=(Attr)attr.item(a);
					if(node.getName().toString().compareTo("height") == 0)
					{
						height = Integer.parseInt(attr.getNamedItem("height").getNodeValue());
						TRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT , height));
					}
					TRow.setHorizontalFadingEdgeEnabled(false);
					TRow.setVerticalScrollBarEnabled(true);
					TRow.setPadding(10, 10, 0, 0);
					TRow.setOrientation(TableLayout.HORIZONTAL);
					if(node.getName().toString().compareTo("BackgroundColor") == 0)
						TRow.setBackgroundColor(Color.parseColor(attr.getNamedItem("BackgroundColor").getNodeValue()));
				}
				llayout.addView(TRow);
	            NodeList tField = fieldNode.getChildNodes();
	            
				for (int j=0;j<tField.getLength();j++) 
				{
					Log.e("ss",j + " f");
					Node ffield = tField.item(j);						
					NamedNodeMap attrf = ffield.getAttributes();
					if(attrf != null)
					{	
						/*
						Log.e("ss",attrf.getNamedItem("type").getNodeValue() + " f");
						if(attrf.getNamedItem("type").getNodeValue().compareTo("Edit") ==0)
						{
							Log.e("ss"," EditText f " );
							EditT = new EditText(this);
							int paddingtop = 0;
							int paddingbottom = 0;
							for (int a=0; a < attrf.getLength(); a++) 
							{
								Attr node=(Attr)attrf.item(a);
								//attrnote[a] = node.getName();
								EditT.setBackgroundColor(Color.TRANSPARENT);
								if(node.getName().toString().compareTo("ID") == 0)
									EditT.setId(Integer.parseInt(attrf.getNamedItem("ID").getNodeValue()));	
								if(node.getName().toString().compareTo("label") == 0)
									EditT.setText(attrf.getNamedItem("label").getNodeValue());
								if(node.getName().toString().compareTo("Color") == 0)
									EditT.setTextColor(Color.parseColor(attrf.getNamedItem("Color").getNodeValue()));
								if(node.getName().toString().compareTo("Size") == 0)
									EditT.setTextSize(Integer.parseInt(attrf.getNamedItem("Size").getNodeValue()));
								if(node.getName().toString().compareTo("width") == 0)
									EditT.setWidth(Integer.parseInt(attrf.getNamedItem("width").getNodeValue()));
								if(node.getName().toString().compareTo("paddingtop") == 0)
									paddingtop = Integer.parseInt(attrf.getNamedItem("paddingtop").getNodeValue());
								if(node.getName().toString().compareTo("paddingbottom") == 0)
									paddingtop = Integer.parseInt(attrf.getNamedItem("paddingbottom").getNodeValue());
								if(node.getName().toString().compareTo("paddingleft") == 0)
									EditT.setPadding(Integer.parseInt(attrf.getNamedItem("paddingleft").getNodeValue()), paddingtop, 0, 0); //(Integer.parseInt(attrf.getNamedItem("width").getNodeValue()));
								if(node.getName().toString().compareTo("BackgroundColor") == 0)
									EditT.setBackgroundColor(Color.parseColor(attrf.getNamedItem("BackgroundColor").getNodeValue())); 
								if(node.getName().toString().compareTo("marginbottom") == 0)
								{	
									LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)EditT.getLayoutParams();
									params.setMargins(0, 0, 0, Integer.parseInt(attrf.getNamedItem("marginbottom").getNodeValue())); //substitute parameters for left, top, right, bottom
									EditT.setLayoutParams(params);
									//EditT.set(Integer.parseInt(attrf.getNamedItem("marginbottom").getNodeValue()), paddingtop, 0, 0);
								}
								//EditT.setTextAlignment(Gravity.RIGHT);
							}							
							TRow.addView(EditT);
						}
						*/
						if(attrf.getNamedItem("type").getNodeValue().compareTo("Text")==0)
						{	
								Log.e("ss"," text vewv f ");
								TextV = new TextView(this);
								int paddingtop = 0;
								int paddingbottom = 0;
								for (int a=0; a < attrf.getLength(); a++) 
								{
									Attr node=(Attr)attrf.item(a);
									//TextV.setBackgroundColor(Color.TRANSPARENT);
									if(node.getName().toString().compareTo("ID") == 0)
										TextV.setId(Integer.parseInt(attrf.getNamedItem("ID").getNodeValue()));
									if(node.getName().toString().compareTo("TextAlign") == 0)
									{
										int TextAlign = 0;
										if (attrf.getNamedItem("TextAlign").getNodeValue().toUpperCase().compareTo("RIGHT") == 0)
											TextAlign = 5;
										if (attrf.getNamedItem("TextAlign").getNodeValue().toUpperCase().compareTo("LEFT") == 0)
											TextAlign = 3;
										if (attrf.getNamedItem("TextAlign").getNodeValue().toUpperCase().compareTo("CENTER") == 0)
											TextAlign = 17;
										Log.e("ss", Gravity.RIGHT + " text vewv f " + Gravity.LEFT + " text vewv f " + Gravity.CENTER + " text vewv f " );
										TextV.setGravity(TextAlign);//(Integer.parseInt(attrf.getNamedItem("TextAlign").getNodeValue()));
									}
									if(node.getName().toString().compareTo("label") == 0)
										TextV.setText(attrf.getNamedItem("label").getNodeValue().toUpperCase());
									if(node.getName().toString().compareTo("width") == 0)
										TextV.setWidth(Integer.parseInt(attrf.getNamedItem("width").getNodeValue()));
									if(node.getName().toString().compareTo("Color") == 0)
										TextV.setTextColor(Color.parseColor(attrf.getNamedItem("Color").getNodeValue()));
									if(node.getName().toString().compareTo("BackgroundColor") == 0)
										TextV.setBackgroundColor(Color.parseColor(attrf.getNamedItem("BackgroundColor").getNodeValue())); 
									if(node.getName().toString().compareTo("Size") == 0)
									TextV.setTextSize(Integer.parseInt(attrf.getNamedItem("Size").getNodeValue()));
									if(node.getName().toString().compareTo("paddingtop") == 0)
										paddingtop = Integer.parseInt(attrf.getNamedItem("paddingtop").getNodeValue());
									if(node.getName().toString().compareTo("paddingbottom") == 0)
										paddingbottom = Integer.parseInt(attrf.getNamedItem("paddingbottom").getNodeValue());
									if(node.getName().toString().compareTo("paddingleft") == 0)
										TextV.setPadding(Integer.parseInt(attrf.getNamedItem("paddingleft").getNodeValue()),0, 0, 0);
									if(node.getName().toString().compareTo("marquee") == 0)
									{
										if(attrf.getNamedItem("marquee").getNodeValue() != null && attrf.getNamedItem("marquee").getNodeValue().compareTo("true")==0) 
										{	
											TextV.setMarqueeRepeatLimit(-1);
											TextV.setEllipsize(TruncateAt.MARQUEE);
											TextV.setFocusableInTouchMode(true);
											TextV.setSingleLine(true);
											TextV.setSelected(true);
											Log.e("ss"," chu chay " + attrf.getNamedItem("marquee").getNodeValue());
										}
									}
									
									
									/*
									if(node.getName().toString().compareTo("marginbottom") == 0)
									{	
										Log.e("ss"," chu chay " + attrf.getNamedItem("marginbottom").getNodeValue());
										LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)TextV.getLayoutParams();
										params.setMargins(0, 0, 0, Integer.parseInt(attrf.getNamedItem("marginbottom").getNodeValue())); //substitute parameters for left, top, right, bottom
										TextV.setLayoutParams(params);
										//EditT.set(Integer.parseInt(attrf.getNamedItem("marginbottom").getNodeValue()), paddingtop, 0, 0);
									}*/
								}
								
								
								//TextV.setHeight(LayoutParams.MATCH_PARENT );
								
							
							TRow.addView(TextV);
						}						
						if(attrf.getNamedItem("type").getNodeValue().compareTo("Image") ==0)
						{
							File imgFile = new  File(attrf.getNamedItem("imgFile").getNodeValue());
							
							if(imgFile.exists()){
								
							    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());						    
							    ImageV = new ImageView(this);
							    ImageV.setPadding(Integer.parseInt(attrf.getNamedItem("paddingleft").getNodeValue()), 0, 0, 0);
								ImageV.setId(Integer.parseInt(attrf.getNamedItem("ID").getNodeValue()));
								ImageV.setImageBitmap(myBitmap);
								
							}
							Log.e("ss"," Image vewv f" + attrf.getNamedItem("imgFile").getNodeValue());
							
							//ImageV.setWidth(Integer.parseInt(attrf.getNamedItem("width").getNodeValue()));
							
							TRow.addView(ImageV);
						}
						if(attrf.getNamedItem("type").getNodeValue().compareTo("DigitalClock") ==0)
						{							
							Clock = new DigitalClock(this);	
							Clock.setWidth(Integer.parseInt(attrf.getNamedItem("width").getNodeValue()));
							Clock.setTextColor(Color.parseColor(attrf.getNamedItem("Color").getNodeValue()));
							Clock.setTextSize(Integer.parseInt(attrf.getNamedItem("Size").getNodeValue()));
							Clock.setPadding(Integer.parseInt(attrf.getNamedItem("paddingleft").getNodeValue()), 0, 0, 0);
							TRow.addView(Clock);
						}						
					}
				}
				
			}
		} catch (Exception e) {
			Log.e("Eree","Error occurred in ProcessForm:" + e.getMessage());
			e.printStackTrace();
			 showMsg(e.getMessage());
		 
		}
	}
	
	private void SetValueDefault() 
	{
		SharedPreferences customSharedPreference = getSharedPreferences("DayConfig.properties", Activity.MODE_PRIVATE);
		customSharedPreference.getString("Day", "");
		Map<String,?> keys = customSharedPreference.getAll();

		for(Map.Entry<String,?> entry : keys.entrySet()){
		            Log.d("map values",entry.getKey() + ": " + 
		                                   entry.getValue().toString());   
		            Log.i("Duong", " begin _" + entry.getKey());
					  if(entry.getKey().compareTo("IpServer") != 0 && entry.getKey().compareTo("IDLine") != 0 && entry.getKey().compareTo("PW") != 0 )
					  {
						  String []value =  entry.getValue().toString().split("/");
						  Log.d(" bbbb ",value.length + "") ;
						  if(value.length > 1)
						  {
							  Log.d(" so luong ",value.toString() + "") ;
							  Log.d(" aaaa ",value[0].toString()  + "  " + value[1].toString() ) ;
							//setText(entry.getKey(),entry.getValue().toString()) ;
							//SetConfig(jsonObj.get("id").toString(), jsonObj.get("t").toString()+"/"+ jsonObj.get("v").toString(), localTime);
							  // HomeActivity.this.SetValue(Integer.parseInt(jsonObj.get("id").toString()), jsonObj.get("t").toString(), jsonObj.get("v").toString());
							SetValue(Integer.parseInt(entry.getKey()), value[0].toString(), value[1].toString());
						  }
					  }
		 }
	}

   
	// load image
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            //Log.v("Duong", namefile);
            if(nguoi == 1)
            {
            	Nguoi1.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture1 = f.getName();
            }
            if(nguoi == 2)
            {
            	Nguoi2.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture2 = f.getName();
            }
            if(nguoi == 3)
            {
            	Nguoi3.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture3 = f.getName();
            }
            if(nguoi == 4)
            {
            	Nguoi4.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture4 = f.getName();
            }
            if(nguoi == 5)
            {
            	Nguoi5.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture5 = f.getName();
            }
            if(nguoi == 6)
            {
            	Nguoi6.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture6 = f.getName();
            }
            cursor.close();
        }
     
     
    }
    
    // Ve anh thanh hinh tron
    private Bitmap DrawCircle() {
		Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        BitmapShader shader = new BitmapShader (bitmap,  TileMode.CLAMP, TileMode.CLAMP);
        Paint paint = new Paint();
        paint.setShader(shader);

        Canvas c = new Canvas(circleBitmap);
        c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
		return circleBitmap;
	}
   
	// get Value giao dien
	private void SetValue(int ID,String type, String content) {
		Log.e("ss"," vao set value " );
		try{
		if(type.compareTo("Text") == 0)
		{
			TextV = (TextView) findViewById(ID);
			TextV.setText(content);
		}
		if(type.compareTo("Edit") == 0)
		{
			EditT = (EditText) findViewById(ID);
			Log.e("ss"," vao edit  " + ID + "//" +  content);
			EditT.setText(content);
		}
		if(type.compareTo("Image") == 0)
		{
			ImageV = (ImageView) findViewById(ID);
			File imgFile = new  File(content);
			
			if(imgFile.exists()){
				
			    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());						    
			    ImageV = new ImageView(this);
			    ImageV.setImageBitmap(myBitmap);
			}
		}
		 }
		 catch (  Exception e) {
			 showMsg(e.getMessage());
		  }
		
	}
	/*
	private void GetValue() {
		
		
		// row gd
		gd1 = (TextView) findViewById(R.id.gd0);
		gd2 = (TextView) findViewById(R.id.gd1);
		gd3 = (TextView) findViewById(R.id.gd2);
		gd4 = (TextView) findViewById(R.id.gd3);
		gd5 = (TextView) findViewById(R.id.gd4);
		gd6 = (TextView) findViewById(R.id.gd5);
		gd7 = (TextView) findViewById(R.id.gd6);
		gd8 = (TextView) findViewById(R.id.gd7);
		gd9 = (TextView) findViewById(R.id.gd8);
		gd10 = (TextView) findViewById(R.id.gd9);
				
		// row A
		A1 = (TextView) findViewById(R.id.Muctieu0);
		ImageA1 = (ImageView) findViewById(R.id.imageButton0);
		A2 = (TextView) findViewById(R.id.Muctieu1);
		ImageA2 = (ImageView) findViewById(R.id.imageButton1);
		A3 = (TextView) findViewById(R.id.Muctieu2);
		ImageA3 = (ImageView) findViewById(R.id.imageButton2);
		A4 = (TextView) findViewById(R.id.Muctieu3);
		ImageA4 = (ImageView) findViewById(R.id.imageButton3);
		A5 = (TextView) findViewById(R.id.Muctieu4);
		ImageA5 = (ImageView) findViewById(R.id.imageButton4);
		A6 = (TextView) findViewById(R.id.Muctieu5);
		ImageA6 = (ImageView) findViewById(R.id.imageButton5);
		A7 = (TextView) findViewById(R.id.Muctieu6);
		ImageA7 = (ImageView) findViewById(R.id.imageButton6);
		A8 = (TextView) findViewById(R.id.Muctieu7);
		ImageA8 = (ImageView) findViewById(R.id.imageButton7);
		A9 = (TextView) findViewById(R.id.Muctieu8);
		ImageA9 = (ImageView) findViewById(R.id.imageButton8);
		A10 = (TextView) findViewById(R.id.Muctieu9);
		ImageA10 = (ImageView) findViewById(R.id.imageButton9);
		
		// Row B		
		ImageB1 = (ImageView) findViewById(R.id.ImgThucTe0);
		ImageB2 = (ImageView) findViewById(R.id.ImgThucTe1);
		ImageB3 = (ImageView) findViewById(R.id.ImgThucTe2);
		ImageB4 = (ImageView) findViewById(R.id.ImgThucTe3);
		ImageB5 = (ImageView) findViewById(R.id.ImgThucTe4);
		ImageB6 = (ImageView) findViewById(R.id.ImgThucTe5);
		ImageB7 = (ImageView) findViewById(R.id.ImgThucTe6);
		ImageB8 = (ImageView) findViewById(R.id.ImgThucTe7);
		ImageB9 = (ImageView) findViewById(R.id.ImgThucTe8);
		ImageB10 = (ImageView) findViewById(R.id.ImgThucTe9);
		
		// Row C
		C1 = (ImageView) findViewById(R.id.ImgTocdo);
		C2 = (ImageView) findViewById(R.id.ImgTocdo1);
		C3 = (ImageView) findViewById(R.id.ImgTocdo2);
		C4 = (ImageView) findViewById(R.id.ImgTocdo3);
		
		// Row D
		D1 = (ImageView) findViewById(R.id.ImgDudoan0);
		D2 = (ImageView) findViewById(R.id.ImgDudoan1);
		D3 = (ImageView) findViewById(R.id.ImgDudoan2);
		D4 = (ImageView) findViewById(R.id.ImgDudoan3);
		D5 = (ImageView) findViewById(R.id.ImgDudoan4);
		D6 = (ImageView) findViewById(R.id.ImgDudoan5);
		D7 = (ImageView) findViewById(R.id.ImgDudoan6);
		D8 = (ImageView) findViewById(R.id.ImgDudoan7);
		D9 = (ImageView) findViewById(R.id.ImgDudoan8);
		D10 = (ImageView) findViewById(R.id.ImgDudoan9);
		
		// row E
		
		E1 = (EditText) findViewById(R.id.txtLuyke1);
		E3 = (ImageView) findViewById(R.id.ImgLuyke3);
		
		// row F
		
		F1 = (EditText) findViewById(R.id.txtMuctieu1);
		F2 = (TextView) findViewById(R.id.vluyke1);
		F3 = (TextView) findViewById(R.id.vluyke2);
		F4 = (EditText) findViewById(R.id.txtMuctieu2);
		
		// row G
		Nguoi1 = (ImageView) findViewById(R.id.imgNguoixuatsac1);		
		Nguoi2 = (ImageView) findViewById(R.id.imgNguoixuatsac2);
		Nguoi3 = (ImageView) findViewById(R.id.imgNguoixuatsac3);
		Nguoi4 = (ImageView) findViewById(R.id.imgNguoixuatsac4);
		Nguoi5 = (ImageView) findViewById(R.id.imgNguoixuatsac5);
		Nguoi6 = (ImageView) findViewById(R.id.imgNguoixuatsac6);
		
		
		// Row H
		chuchay = (TextView) findViewById(R.id.shadowtext);
    	Gopytext = (EditText) findViewById(R.id.txtshadowtext);
		
	}
*/
	
	//Get file config
	private String GetConfig(String Key) {
		SharedPreferences customSharedPreference = getSharedPreferences("DayConfig.properties", Activity.MODE_PRIVATE);
		
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		Date currentLocalTime = cal.getTime();		
		DateFormat date = new SimpleDateFormat("dd-MM-yyyy");  
		date.setTimeZone(TimeZone.getTimeZone("GMT")); 
		String localTime =  date.format(currentLocalTime);
		Log.d(" Ngay hien tai ",localTime + Key);
		Log.d(" Ngay hien tai ",customSharedPreference.getString("Day", "") + Key);
		Log.d(" Ngay file ",customSharedPreference.getString("Day", ""));		
		if (customSharedPreference.getString("Day", "").compareTo(localTime) != 0 )
		{	
			customSharedPreference = getSharedPreferences("PecasConfig.properties", Activity.MODE_PRIVATE);
			Log.d(" PecasConfig ","read PecasConfig");		
			return customSharedPreference.getString(Key, "");
		}
		else
		{
			Log.d(" PecasConfig ","teffsfsfs");
			return customSharedPreference.getString(Key, "");
		}
		/*
		 bach kup
		  context = this;
		assetsPropertyReader = new AssetsPropertyReader(context);
		prop = assetsPropertyReader.getProperties("DayConfig.properties");
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		Date currentLocalTime = cal.getTime();		
		DateFormat date = new SimpleDateFormat("dd-MM-yyyy");  
		date.setTimeZone(TimeZone.getTimeZone("GMT")); 
		String localTime = date.format(currentLocalTime);
		Log.d(" Ngay hien tai ",localTime);
		Log.d(" Ngay file ",prop.getProperty("Day").toString());
		if (prop.getProperty("Day").compareTo(localTime) != 0)
		{
			prop.clear();
			assetsPropertyReader = new AssetsPropertyReader(context);
			prop = assetsPropertyReader.getProperties("PecasConfig.properties");
		}
		return prop.getProperty(Key);*/
		
		
	}

	// Set file Config
	private void SetConfig(String Key,String Value) {		
		SharedPreferences customSharedPreference = getSharedPreferences("PecasConfig.properties", Activity.MODE_PRIVATE);
		  SharedPreferences.Editor editor = customSharedPreference.edit();
		  editor.putString(Key, Value);
		   editor.commit();
	}
	private void SetConfig(String Key,String Value,String Day) {
				
		SharedPreferences customSharedPreference = getSharedPreferences("DayConfig.properties", Activity.MODE_PRIVATE);
		  SharedPreferences.Editor editor = customSharedPreference.edit();
		  editor.putString(Key, Value);
		  editor.putString("Day", Day);
		  editor.commit();
	}
	
	// An hien giai doan tren giao dien
	private void setVisible(int view, boolean VISIBLE) {
		int t;		
		if (VISIBLE)
			 t = android.view.View.VISIBLE;
		else
			t =  android.view.View.INVISIBLE;		
		if (view == R.id.Muctieu0)
		{
			
			A1.setVisibility(t);			
			ImageA1.setVisibility(t);
			ImageB1.setVisibility(t);
			D1.setVisibility(t);
			gd1.setVisibility(t);
		}
		else if (view ==  R.id.Muctieu1)
		{
			A2.setVisibility(t);
			ImageA2.setVisibility(t);
			ImageB2.setVisibility(t);
			D2.setVisibility(t);
			gd2.setVisibility(t);
		}
		else if (view == R.id.Muctieu2)
		{
			A3.setVisibility(t);
			ImageA3.setVisibility(t);
			ImageB3.setVisibility(t);
			D3.setVisibility(t);
			gd3.setVisibility(t);
		}
		else if (view == R.id.Muctieu3)
		{
			A4.setVisibility(t);
			ImageA4.setVisibility(t);
			ImageB4.setVisibility(t);
			D4.setVisibility(t);
			gd4.setVisibility(t);
		}
		else if (view == R.id.Muctieu4)
		{
			A5.setVisibility(t);
			ImageA5.setVisibility(t);
			ImageB5.setVisibility(t);
			D5.setVisibility(t);
			gd5.setVisibility(t);
		}
		else if (view == R.id.Muctieu5)
		{
			A6.setVisibility(t);
			ImageA6.setVisibility(t);
			ImageB6.setVisibility(t);
			D6.setVisibility(t);
			gd6.setVisibility(t);
		}
		else if (view == R.id.Muctieu6)
		{
			A7.setVisibility(t);
			ImageA7.setVisibility(t);
			ImageB7.setVisibility(t);
			D7.setVisibility(t);
			gd7.setVisibility(t);
		}
		else if (view == R.id.Muctieu7)
		{
			A8.setVisibility(t);
			ImageA8.setVisibility(t);
			ImageB8.setVisibility(t);
			D8.setVisibility(t);
			gd8.setVisibility(t);
		}
		else if (view == R.id.Muctieu8)
		{
			A9.setVisibility(t);
			ImageA9.setVisibility(t);
			ImageB9.setVisibility(t);
			D9.setVisibility(t);
			gd9.setVisibility(t);
		}
		else 
		{
			A10.setVisibility(t);
			ImageA10.setVisibility(t);	
			ImageB10.setVisibility(t);	
			D10.setVisibility(t);
			gd10.setVisibility(t);
		}
	}
	
	private void setText(String view, String content) {
		
	}
	// Set Gia Tri
	/*
	private void setText(String view, String content) {
		
		if(view.compareTo("01") ==0)
			gd1.setText(content);
		else if(view.compareTo("02") ==0)
			gd2.setText(content);
		else if(view.compareTo("03") ==0)
			gd3.setText(content);
		else if(view.compareTo("04") ==0)
			gd4.setText(content);
		else if(view.compareTo("05") ==0)
			gd5.setText(content);
		else if(view.compareTo("06") ==0)
			gd6.setText(content);
		else if(view.compareTo("07") ==0)
			gd7.setText(content);
		else if(view.compareTo("08") ==0)
			gd8.setText(content);
		else if(view.compareTo("09") ==0)
			gd9.setText(content);
		else if(view.compareTo("010") ==0)
			gd10.setText(content);
		else if(view.compareTo("11") ==0)
			A1.setText(content);
		else if(view.compareTo("12") ==0)
			A2.setText(content);
		else if(view.compareTo("13") ==0)
			A3.setText(content);
		else if(view.compareTo("14") ==0)
			A4.setText(content);
		else if(view.compareTo("15") ==0)
			A5.setText(content);
		else if(view.compareTo("16") ==0)
			A6.setText(content);
		else if(view.compareTo("17") ==0)
			A7.setText(content);
		else if(view.compareTo("18") ==0)
			A8.setText(content);
		else if(view.compareTo("19") ==0)
			A9.setText(content);
		else if(view.compareTo("110") ==0)
			A10.setText(content);
		else if(view.compareTo("21") ==0)
			ImageB1.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("22") ==0)		{			
			ImageB2.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));		}
		else if(view.compareTo("23") ==0)
			ImageB3.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("24") ==0)
			ImageB4.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("25") ==0)
			ImageB5.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("26") ==0)
			ImageB6.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("27") ==0)
			ImageB7.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("28") ==0)
			ImageB8.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("29") ==0)
			ImageB9.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("210") ==0)
			ImageB10.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("31") ==0 )
		{	
			C1.setColorFilter(0x55ffffff);
			C3.setColorFilter(0x55000000);
			C2.setColorFilter(0x55000000);
			C4.setColorFilter(0x55000000);		
		}
		else if (view.compareTo("32") ==0)
		{
			C2.setColorFilter(0x55ffffff);
			C3.setColorFilter(0x55000000);
			C4.setColorFilter(0x55000000);
			C1.setColorFilter(0x55000000);	
		}
		else if ( view.compareTo("33") ==0 )
		{
			C3.setColorFilter(0x55ffffff);
			C2.setColorFilter(0x55000000);
			C4.setColorFilter(0x55000000);
			C1.setColorFilter(0x55000000);	
		}
		else if (view.compareTo("34") ==0)
		{
			C4.setColorFilter(0x55ffffff);
			C3.setColorFilter(0x55000000);
			C2.setColorFilter(0x55000000);
			C1.setColorFilter(0x55000000);
		}			
		else if(view.compareTo("41") ==0)
			D1.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("42") ==0)		{			
			D2.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));		}
		else if(view.compareTo("43") ==0)
			D3.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("44") ==0)
			D4.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("45") ==0)
			D5.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("46") ==0)
			D6.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("47") ==0)
			D7.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("48") ==0)
			D8.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("49") ==0)
			D9.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("410") ==0)
			D10.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("51") ==0)
		{
			E1.setText(content);
		}
		else if(view.compareTo("52") ==0)
		{
			E3.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("61") ==0)
		{
			F1.setText(content);
		}
		else if(view.compareTo("62") ==0)
		{
			F4.setText(content);			
		}
		else if(view.compareTo("63") ==0)
		{
			F2.setText(content);
		}
		else if(view.compareTo("64") ==0)
		{
			F3.setText(content);
		}
		else if(view.compareTo("71") ==0)
		{
			Nguoi1.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("72") ==0)
		{
			Nguoi2.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("73") ==0)
		{
			Nguoi3.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("74") ==0)
		{
			Nguoi4.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("75") ==0)
		{
			Nguoi5.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("76") ==0)
		{
			Nguoi6.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		}
		else if(view.compareTo("81") ==0)
		{
			chuchay.setText(content);
			Gopytext.setText(content);
			chuchay.setSelected(true);	
		}
	}
	*/
	
    private String Getdata() {
		JSONObject data = new JSONObject();
    	JSONArray array = new JSONArray();
    	
    	try {
    		array.put(picture1);
        	array.put( picture2);
        	array.put( picture3);
        	array.put( picture4);
        	array.put( picture5);
        	array.put( picture6);
        	data.put("id", GetConfig("IDLine"));
			data.put("i", 1);
			data.put("tt",E1.getText().toString() );
			data.put("mt1",F1.getText().toString() );
			data.put("mt2",F4.getText().toString() );
			data.put("xs",array);
			data.put("gy",Gopytext.getText().toString());
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data.toString();
	}

	

	// Tao Socket
    @SuppressLint("HandlerLeak")
   	class ReceivedThread extends Thread {
   		ReceivedHandler handler = new ReceivedHandler();

   		@Override
   		public void run() {
   			Message msg = new Message();
   			Bundle args = new Bundle();
   			try {
   				String retVal = receivedData();
   				msg.what = 0;
   				args.putString("V", retVal);
   				msg.setData(args);
   				handler.sendMessage(msg);
   			} catch (IOException e) {
   				msg.what = 1;
   				args.putString("V", e.getMessage());
   				msg.setData(args);
   				handler.sendMessage(msg);
   			}
   			super.run();
   		}
   	}
       
       private String receivedData() throws IOException {
   		String res = "";   		
   		byte[] buffer = new byte[MAX_UDP_DATAGRAM_LEN];
   		//Log.i("Duong nhan tin hieu server", "Bat dau lan nghe" );	
   		DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
   		udpReceiver.receive(dp);
   		res = new String(buffer, 0, dp.getLength());
   		//Log.i("Duong nhan tin hieu server", res );	
   		return res;
   	}
       
       @SuppressWarnings({ "deprecation", "unused" })
   	private String getLocalIpAddress() {

   		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

   		// Get WiFi status
   		WifiInfo info = wifi.getConnectionInfo();

   		return Formatter.formatIpAddress(info.getIpAddress());
   	}

       private void setUpIOStreams() throws IOException {
   		udpReceiver = new DatagramSocket(UDP_SERVER_PORT);
   		//UDP_SERVER_IP = GetConfig("IpServer");
   	}
       
       @SuppressLint("HandlerLeak")
   	public class ReceivedHandler extends Handler {
   		@Override
   		public void handleMessage(Message msg) {
   			Log.i("Duong", "handleMessage");	
   			switch (msg.what) {
   			case FINISHED_RECEIVER:
   				//setText(appendText, msg.getData().get("V").toString());
   				try {   					
					JSONObject jsonObj = new JSONObject(msg.getData().get("V").toString());					
					SetValue(jsonObj);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
   				new ReceivedThread().start();
   				break;

   			case 1:
   				showMsg(msg.getData().get("V").toString());
   				new ReceivedThread().start();
   				break;
   			}
   		}

		private void SetValue(JSONObject jsonObj) {
			// TODO Auto-generated method stub
			try {
					
				Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
				Date currentLocalTime = cal.getTime();		
				DateFormat date = new SimpleDateFormat("dd-MM-yyyy");  
				date.setTimeZone(TimeZone.getTimeZone("GMT")); 
				String localTime = date.format(currentLocalTime); 
				Log.i("Duong", jsonObj.get("i").toString());
				if(jsonObj.get("i").toString().trim().compareTo("1")==0)
				{		
					Log.i("Duong", jsonObj.get("id").toString() + " " + jsonObj.get("t").toString() + " " + jsonObj.get("t").toString()+"/"+ jsonObj.get("v").toString());				
					//setText(jsonObj.get("r").toString()+jsonObj.get("c").toString(), jsonObj.get("v").toString());
					Log.i("Duong", jsonObj.get("id").toString() + "/" + jsonObj.get("t").toString() + "/" + jsonObj.get("v").toString());
					HomeActivity.this.SetValue(Integer.parseInt(jsonObj.get("id").toString()), jsonObj.get("t").toString(), jsonObj.get("v").toString());
					SetConfig(jsonObj.get("id").toString(), jsonObj.get("t").toString()+"/"+ jsonObj.get("v").toString(), localTime);
				}
				else if(jsonObj.get("i").toString().trim().compareTo("0")==0)
				{
					if (jsonObj.get("v").toString().compareTo("?")==0)
					{
						Log.i("Duong Tra Chuyen", jsonObj.get("v").toString());
						JSONObject data = new JSONObject();
				    	JSONArray array = new JSONArray();
				    	try {
				    		data.put("i", 0);
				        	data.put("id", GetConfig("IDLine"));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						new LongOperation().execute("2", data.toString() );
					}
					/*
					if (jsonObj.get("n").toString().compareTo("SoGiaiDoan")==0)
					{
						SetGiaiDoan(jsonObj.get("v").toString());
						Log.i("Duong SoGiaiDoan", jsonObj.get("n").toString() + "_" + jsonObj.get("v").toString());
					}
					
					Log.i("Duong", jsonObj.get("n").toString() + "_" + jsonObj.get("v").toString());		
					SetConfig(jsonObj.get("n").toString(), jsonObj.get("v").toString());
					SetConfig(jsonObj.get("n").toString(), jsonObj.get("v").toString(),localTime);
					//SetGiaiDoan(jsonObj.get("v").toString());
					SetConfig(jsonObj.get("id").toString(), jsonObj.get("t").toString()+"/"+ jsonObj.get("v").toString(), localTime);
					*/
				}
				
				else
				{
					//Nhan file anh Nhan Vien
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
   	}
    public void showMsg(String msg) {
   		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
   	}
   	private String sendDataOverConnection(String sentence) throws IOException {
   		
   		
   		//Log.i("Duong", isconnect.toString() );
   		if(isconnect)
   			setUpIOStreams();
   		DatagramSocket ds = null;
   		try {
   			ds = new DatagramSocket();
   			//Log.i("Duong", "SERVER : "  + UDP_SERVER_IP  + " PORT : " + UDP_SERVER_PORT + "_ IP Client " + getLocalIpAddress());
   			InetAddress serverAddr = InetAddress.getByName(GetConfig("IpServer"));
   			DatagramPacket dp = new DatagramPacket(sentence.getBytes(),
   					sentence.length(), serverAddr, UDP_SERVER_PORT);
   			ds.send(dp);
   			ds.close();
   			//Log.i("Duong", "SERVER : "  + UDP_SERVER_IP  + " PORT : " + UDP_SERVER_PORT + sentence );
   		} catch (SocketException e) {
   			e.printStackTrace();
   		} catch (UnknownHostException e) {
   			e.printStackTrace();
   		} catch (IOException e) {
   			throw e;
   		} catch (Exception e) {
   			e.printStackTrace();
   		} finally {
   			if (ds != null)
   				ds.close();
   		}

   		sentence = ("OUT TO SERVER: " + sentence);
   		return sentence;

   	}
       private class LongOperation extends AsyncTask<String, Void, String> {

   		@Override
   		protected String doInBackground(String... params) {
   			//Log.i("Duong", "Connet socket " +  params[0]);
   			String res = params[0];
   			if (params[0] == "1") {
   				try {
   					setUpIOStreams();
   				} catch (IOException ex) {
   					res = ex.toString();
   				}
   				// enableConnection();
   			} else if (params[0] == "2") {
   				try {
   					res = "2:" + sendDataOverConnection(params[1]);
   					
   					Log.i("Duong", res);
   				} catch (IOException ex) {
   					res = ex.toString();
   				}

   			}
   			return res;
   		}

   		@Override
   		protected void onPostExecute(String result) {
   			//Log.i("Duong", "Connet socket");
   			if (result == "1") {
   				//Log.i("Duong", "Connet socket Start");
   				ReceivedThread th = new ReceivedThread();
   				th.start();
   				// new ReceiverOperation().execute("");
   			} else if (result.charAt(0) == '2') {
   				//setText(appendText, result.substring(2)); can sua lai
   				// new LongOperation().execute("3");
   				
   			} else {
   				
   			}

   		}

   		@Override
   		protected void onPreExecute() {
   		}

   		@Override
   		protected void onProgressUpdate(Void... values) {
   		}

   	}
}